/**
 * @author: zzj
 * @date: 2020-03-12 10:32:33
 * @version: 1.0
 */
import Vue from 'vue';

const OSS_URL = process.env.VUE_APP_OSS_URL;
const defaultImg = require('../img/defaultImg.png');
const defaultAvatar = require('../img/avatar.png');

const intersectionObserver = new IntersectionObserver(function (entries) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      let el = entry.target;
      loadImg(el, el.src);
      intersectionObserver.unobserve(el);
    }
  });
});

function loadImg(el, initImg, src) {
  let newImg = new Image();
  el.src = initImg;
  newImg.onload = function () {
    el.src = this.src;
  };
  newImg.src = src;
}

//图片模式mode详见：https://help.aliyun.com/document_detail/44688.html?spm=a2c4g.11186623.6.1181.e3803168l0gWII
Vue.directive('src', function (el, binding) {
  let {value, arg} = binding;
  let isImg = el.tagName === "IMG";
  let isFullPath = /^http/ig.test(value);
  let src = isFullPath ? value : Vue.prototype.$oss.signatureUrl(value,{expires: 14200});
  if (isImg) {
    let isAvatar = arg === 'avatar';
    let initImg = isAvatar ? defaultAvatar : defaultImg;
    let size = Object.keys(binding.modifiers);
    let mode = isAvatar ? 'fill' : arg;
    let suffix = (mode && size.length && !isFullPath) ? `?x-oss-process=image/resize,m_${mode}${size[0] ? ',' + size[0] : ''}${size[1] ? ',' + size[1] : ''}` : "";
    let oldSrc = el.dataset.src;
    el.dataset.src = value;
    if (!value) return el.src = initImg;
    if (oldSrc === value) return;
    let lazy = el.getAttribute("lazy");
    let isLazy = lazy === "" || lazy === "true";
    if (isLazy) {
      el.src = initImg;
      intersectionObserver.observe(el);
    } else {
      loadImg(el, initImg, src + suffix);
    }
  } else {
    if (el.dataset.src === value) return;
    el.dataset.src = value;
    el.src = src;
  }
});

